//
//  AppDelegate.m
//  TripGo
//
//  Created by dllo on 15/7/20.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "TravelViewController.h"
#import "TacticsViewController.h"
#import "UserViewController.h"
#import "SpecialViewController.h"
#import "Database.h"
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"
#import "WeiboApi.h"
#import "WeiboSDK.h"
#import <RennSDK/RennSDK.h>
#import <CoreLocation/CoreLocation.h>

#define USERDEFAULT [NSUserDefaults standardUserDefaults]
@interface AppDelegate () <CLLocationManagerDelegate>
@property (nonatomic, retain) CLLocationManager *locationManager;
@end

@implementation AppDelegate
- (void)dealloc
{
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    UITabBarController *tabBarC = [[UITabBarController alloc] init];
    
    //    CGRect frame = CGRectMake(0, self.window.bounds.size.height - 49, self.window.bounds.size.width, 49);
    //    UIView *view = [[UIView alloc] initWithFrame:frame];
    //    UIImage *tabBarBackgroundImage = [UIImage imageNamed:@"11.jpg"];
    //    UIColor *color = [[UIColor alloc] initWithPatternImage:tabBarBackgroundImage];
    //    [view setBackgroundColor:color];
    //    [color release];
    //    [tabBarC.view insertSubview:view atIndex:1];
    //    [view release];
    
    //    NSArray *array = [tabBarC.view subviews];
    //    UITabBar *tabBar = [array objectAtIndex:0];
    //    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
    //    UIImage *image = [UIImage imageWithContentsOfFile:sourcePath ];
    //    tabBar.layer.contents = (id)image.CGImage;
    
    
    TravelViewController *travelVc = [[TravelViewController alloc] init];
    SpecialViewController *specialVc = [[SpecialViewController alloc] init];
    TacticsViewController *tacticsVc = [[TacticsViewController alloc] init];
    UserViewController *userVc = [[UserViewController alloc] init];
    
    //设置tabBar
    travelVc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"游记" image:[UIImage imageNamed:@"iconfont-youji-2"] tag:1000];
    specialVc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"专题" image:[UIImage imageNamed:@"iconfont-special4"] tag:1001];
    tacticsVc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"攻略" image:[UIImage imageNamed:@"iconfont-jingyingzhucedi"] tag:1002];
    userVc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"更多" image:[UIImage imageNamed:@"iconfont-gengduo-2"] tag:1003];
    
    
    //设置选中的title颜色
    [[UITabBar appearance] setTintColor:[UIColor colorWithRed:56 / 255.0 green:152 / 255.0 blue:135 / 255.0 alpha:1]];
    
    UINavigationController *navi1 = [[UINavigationController alloc] initWithRootViewController:travelVc];
    UINavigationController *navi2 = [[UINavigationController alloc] initWithRootViewController:specialVc];
    UINavigationController *navi3 = [[UINavigationController alloc] initWithRootViewController:tacticsVc];
    UINavigationController *navi4 = [[UINavigationController alloc] initWithRootViewController:userVc];
    
    
    tabBarC.viewControllers = @[navi1, navi2, navi3, navi4];
    self.window.rootViewController = tabBarC;

    [travelVc release];
    [specialVc release];
    [tacticsVc release];
    [userVc release];
    [navi1 release];
    [navi2 release];
    [navi3 release];
    [navi4 release];
    [tabBarC release];
    
    // 建立数据库
    [Database openDataBase];
    [Database createTable];
    
    // 定位
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = 1000.0f;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    } else {
        NSLog(@"请开启定位功能");
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [_locationManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
    }
    [_locationManager startUpdatingLocation];
    
    
    [ShareSDK registerApp:@"8f12ebc45216"];//字符串api20为您的ShareSDK的AppKey
    
    //添加新浪微博应用 注册网址 http://open.weibo.com
    [ShareSDK connectSinaWeiboWithAppKey:@"568898243"
                               appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                             redirectUri:@"http://www.sharesdk.cn"];
//    //当使用新浪微博客户端分享的时候需要按照下面的方法来初始化新浪的平台 （注意：2个方法只用写其中一个就可以）
//    [ShareSDK  connectSinaWeiboWithAppKey:@"568898243"
//                                appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
//                              redirectUri:@"http://www.sharesdk.cn"
//                              weiboSDKCls:[WeiboSDK class]];
    
    
    //添加QQ空间应用  注册网址  http://connect.qq.com/intro/login/
    [ShareSDK connectQZoneWithAppKey:@"100371282"
                           appSecret:@"aed9b0303e3ed1e27bae87c33761161d"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    
    
    //添加微信应用  http://open.weixin.qq.com
    [ShareSDK connectWeChatWithAppId:@"wx4868b35061f87885"
                           appSecret:@"64020361b8ec4c99936c0e3999a9f249"
                           wechatCls:[WXApi class]];
    
//    //添加搜狐微博应用  注册网址  http://open.t.sohu.com
//    [ShareSDK connectSohuWeiboWithConsumerKey:@"SAfmTG1blxZY3HztESWx"
//                               consumerSecret:@"yfTZf)!rVwh*3dqQuVJVsUL37!F)!yS9S!Orcsij"
//                                  redirectUri:@"http://www.sharesdk.cn"];
    
    //添加豆瓣应用  注册网址 http://developers.douban.com
    [ShareSDK connectDoubanWithAppKey:@"07d08fbfc1210e931771af3f43632bb9"
                            appSecret:@"e32896161e72be91"
                          redirectUri:@"http://dev.kumoway.com/braininference/infos.php"];
    
    //添加人人网应用 注册网址  http://dev.renren.com
    [ShareSDK connectRenRenWithAppId:@"226427"
                              appKey:@"fc5b8aed373c4c27a05b712acba0f8c3"
                           appSecret:@"f29df781abdd4f49beca5a2194676ca4"
                   renrenClientClass:[RennClient class]];
    
//    //添加开心网应用  注册网址 http://open.kaixin001.com
//    [ShareSDK connectKaiXinWithAppKey:@"358443394194887cee81ff5890870c7c"
//                            appSecret:@"da32179d859c016169f66d90b6db2a23"
//                          redirectUri:@"http://www.sharesdk.cn/"];
//    
//    //添加Instapaper应用   注册网址  http://www.instapaper.com/main/request_oauth_consumer_token
//    [ShareSDK connectInstapaperWithAppKey:@"4rDJORmcOcSAZL1YpqGHRI605xUvrLbOhkJ07yO0wWrYrc61FA"
//                                appSecret:@"GNr1GespOQbrm8nvd7rlUsyRQsIo3boIbMguAl9gfpdL0aKZWe"];
    
//    //添加有道云笔记应用  注册网址 http://note.youdao.com/open/developguide.html#app
//    [ShareSDK connectYouDaoNoteWithConsumerKey:@"dcde25dca105bcc36884ed4534dab940"
//                                consumerSecret:@"d98217b4020e7f1874263795f44838fe"
//                                   redirectUri:@"http://www.sharesdk.cn/"];
    
    //添加Facebook应用  注册网址 https://developers.facebook.com
    [ShareSDK connectFacebookWithAppKey:@"107704292745179"
                              appSecret:@"38053202e1a5fe26c80c753071f0b573"];
    
    //添加Twitter应用  注册网址  https://dev.twitter.com
    [ShareSDK connectTwitterWithConsumerKey:@"mnTGqtXk0TYMXYTN7qUxg"
                             consumerSecret:@"ROkFqr8c3m1HXqS3rm3TJ0WkAJuwBOSaWhPbZ9Ojuc"
                                redirectUri:@"http://www.sharesdk.cn"];
    
    [_window release];
    [self showGuide];
    return YES;
}

//调用引导页面方法
-(void)showGuide
{
    if ([VAGuideView shouldShowGuide]) {
        NSMutableArray *arrImage = [NSMutableArray array];
        
#pragma - mark  这里填你们到导航图  for循环控制张数   后面是图片的名字
        for (int i=0; i<4; i++) {
            UIImage *image = [UIImage imageWithFileName:[NSString stringWithFormat:@"%@-guide-%d-v", @"iPhone5", i] ofType:@"png"];
            [arrImage addObject:image];
        }
        _guideView = [VAGuideView guideViewWithFrame:self.window.bounds arrImages:arrImage space:30];
        NSLog(@"%f", _guideView.frame.size.height);
        _guideView.contentMode = UIViewContentModeScaleToFill;
        //引导页背景图
        UIImageView *imageViewBg = [[UIImageView alloc] initWithFrame:_guideView.bounds];
        
#pragma - mark 这里是播放导航图时的背景图片  换成你们自己的即可
        imageViewBg.image = [UIImage imageNamed:@"iPhone_guide_bg"];
        imageViewBg.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        imageViewBg.contentMode = UIViewContentModeScaleAspectFill;
        imageViewBg.clipsToBounds = YES;
        [_guideView insertSubview:imageViewBg atIndex:0];
        _guideView.imageContentMode = UIViewContentModeCenter;
        
        //最后一页进入应用按钮
        UIButton *btnStart = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnStart setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
#pragma - mark  这是最后一页导航图上面按钮的控制，图片，文字，位置 点击方法（点击之后才创建首页视图,因为导航图消失时有动画效果，建议加个定时器，1秒之后才开始创建视图）
        [btnStart setBackgroundImage:[UIImage imageNamed:@"iPhone-anniubox-2"] forState:UIControlStateNormal];
        [btnStart setTitle:@"即刻启程" forState:UIControlStateNormal];
        btnStart.frame = CGRectMake(0, 580, 160, 40);
        [btnStart addTarget:self action:@selector(touchStartButton) forControlEvents:UIControlEventTouchUpInside];
        btnStart.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin;
        [_guideView addButtonAtLastPage:btnStart];
        if (_guideView && arrImage.count>0) {
            _currInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
            _lockRotate = YES;
            [self.window addSubview:_guideView];
            double delayInSeconds = 0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [_guideView startAnimationWithDuration:3
                                 animationComplecation:nil
                                            didDismiss:^{
                                                _lockRotate = NO;
                                            }];
            });
        }
    }
#pragma - mark 不是第一次启动，直接创建本页面视图
    else
    {
        _currInterfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
        _lockRotate = YES;
        [self createMainPageView];
    }
}
-(void)touchStartButton
{
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(createMainPageView) userInfo:nil repeats:NO];
}


-(void)createMainPageView
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0 , 300, self.window.frame.size.width, 60)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont boldSystemFontOfSize:30];
    [self.window addSubview:label];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    // 获取国家, 城市等信息 (其他属性点进去看)
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            NSArray *addressArray = [placemark.addressDictionary objectForKey:@"FormattedAddressLines"];
            NSMutableString *addR = [[NSMutableString alloc] init];
            for (int i = 0; i < addressArray.count; i++) {
                [addR appendString:addressArray[i]];
            }
            //            NSLog(@"&******%@", addressArray);
            NSString *lat = [NSString stringWithFormat:@"%f", coor.latitude];
            NSString *lng = [NSString stringWithFormat:@"%f", coor.longitude];
            [USERDEFAULT setObject:lat forKey:@"lat"];
            [USERDEFAULT setObject:lng forKey:@"lng"];
        }
    }];
    [_locationManager stopUpdatingLocation];
}


// 定位失误
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        NSLog(@"wrong");
    }
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
